package cn.like.datasource.support;

import cn.like.base.BaseEntity;
import cn.like.base.auth.AuthContext;
import cn.like.base.support.id.IdGenerator;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * mybatis 自动填充
 *
 * @author like 980650920@qq.com
 * @date 2021/7/10 10:45
 */
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    private final IdGenerator idGenerator;
    private final AuthContext authContext;

    public MyMetaObjectHandler(IdGenerator idGenerator, AuthContext authContext) {
        this.idGenerator = idGenerator;
        this.authContext = authContext;
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, BaseEntity.CREATE_TIME, LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, BaseEntity.CREATE_USER, Long.class, authContext.getUserId());
        this.strictUpdateFill(metaObject, BaseEntity.UPDATE_TIME, LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, BaseEntity.UPDATE_USER, Long.class, authContext.getUserId());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, BaseEntity.UPDATE_TIME, LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, BaseEntity.UPDATE_USER, Long.class, authContext.getUserId());
    }
}
